package com.cs.beneficios.web.action;
import com.cs.beneficios.business.entity.BeneficiarioDAO;
import com.cs.beneficios.business.entity.VflexDAO;
import com.cs.beneficios.business.model.BeneficiarioVO;
import com.cs.beneficios.common.ConnectionFactory;

import com.cs.paoyer.administration.exception.AdministrationUserException;
import com.cs.paoyer.administration.util.AccessControl;
import com.cs.paoyer.common.exception.CommonUserException;
import com.cs.paoyer.common.exception.UserException;
import java.io.IOException;

import java.sql.SQLException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

public class ConsultarBeneficiarioAction extends Action
{
  /**
   * This is the main action called from the Struts framework.
   * @param mapping The ActionMapping used to select this instance.
   * @param form The optional ActionForm bean for this request.
   * @param request The HTTP Request we are processing.
   * @param response The HTTP Response we are processing.
   * @return 
   * @throws java.io.IOException
   * @throws javax.servlet.ServletException
   */
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
  {
    
    
    ActionMessages messages = new ActionMessages();
    try
    {
      	AccessControl access = new AccessControl();
        access.validateAccess(mapping,request,response);
        
        //ConnectionFactory cf = new ConnectionFactory("beneficios","beneficios");
		ConnectionFactory cf = new ConnectionFactory();
    
        BeneficiarioVO objBeneVO = new BeneficiarioVO();
        String strCode =  request.getParameter("code");
        //System.err.println("CODIGO DE PARAMETRO "+strCode);
        HttpSession session = request.getSession();
        Collection beneSelected = new ArrayList();
        List beneficiariosList = (List)session.getAttribute("beneficiarios");
        //List beneficiariosList = (List)request.getAttribute("beneficiarios");
        Collection comunas=null;
        Collection barrios=null;
        Collection zonas=null;
        String opcion = request.getParameter("opcion");
        boolean encontro = false;
        if(beneficiariosList != null && beneficiariosList.size() > 0)
        {
          for(Iterator i = beneficiariosList.iterator(); i.hasNext();)
          {
            objBeneVO = (BeneficiarioVO)i.next();
            if(strCode.equals(objBeneVO.getCode().toString()))
            {
              beneSelected.add(objBeneVO);
              encontro = true;
              break;
            }
          }
        }

        
        if(!encontro)
        {
          objBeneVO = new BeneficiarioVO();
          objBeneVO.setCode(new Long(strCode));
          try
            {
              BeneficiarioDAO objBeneDAO = new BeneficiarioDAO(cf);
              beneSelected = objBeneDAO.findBeneficiarioByCriterea(objBeneVO,"ConsultarBeneficiario");
              List bene = (List)beneSelected;
              objBeneVO = (BeneficiarioVO) bene.get(0);
              cf.closeConnection(objBeneDAO.getConn());
            }catch(SQLException e)
            {
				System.err.println("/******** TDSUB - cwsub");
				e.printStackTrace();
				System.err.println("TDSUB - cwsub ********/");
            }
        }
        
        request.setAttribute("code",objBeneVO.getCode().toString());
        request.setAttribute("tipoDocumento",objBeneVO.getTipoDocumento());
        request.setAttribute("numeroDocumento",objBeneVO.getNumeroDocumento());
        request.setAttribute("primer_nombre",objBeneVO.getNombre1());
        request.setAttribute("segundo_nombre",objBeneVO.getNombre2());
        request.setAttribute("primerApellido",objBeneVO.getPrimerApellido());     
        request.setAttribute("segundoApellido",objBeneVO.getSegundoApellido());
        request.setAttribute("telefono",objBeneVO.getTelefono());
        request.setAttribute("dirDescriptiva",objBeneVO.getDirDescriptiva());
        String dirEncasillada =  objBeneVO.getDirEncasillada();
        // CR 0037 BB   0107  B 007 0001001
        // 0123456789012345678901234567891234
        if((Object)dirEncasillada != null)
        {
          int a = dirEncasillada.length();
          if(dirEncasillada.length() == 32)
          {
            String tipo = dirEncasillada.substring(0,2);
            String vOr = dirEncasillada.substring(3,4);
            String vNro = dirEncasillada.substring(4,7);
            String vAp = dirEncasillada.substring(8,10);
            String cOr = dirEncasillada.substring(13,14);
            String cNro = dirEncasillada.substring(14,17);
            String cAp = dirEncasillada.substring(18,20);
            String placa = dirEncasillada.substring(21,24);
            String bloque = dirEncasillada.substring(25,27);
            String interior = dirEncasillada.substring(27,32);
            request.setAttribute("tipo",tipo);
            request.setAttribute("vOr",vOr);
            request.setAttribute("vNro",vNro);
            request.setAttribute("vAp",vAp);
            request.setAttribute("cOr",cOr);
            request.setAttribute("cNro",cNro);
            request.setAttribute("cAp",cAp);
            request.setAttribute("placa",placa);
            request.setAttribute("bloque",bloque);
            request.setAttribute("interior",interior);
          }else
          {
            request.setAttribute("tipo","");
            request.setAttribute("vOr","");
            request.setAttribute("vNro","");
            request.setAttribute("vAp","");
            request.setAttribute("cOr","");
            request.setAttribute("cNro","");
            request.setAttribute("cAp","");
            request.setAttribute("placa","");
            request.setAttribute("bloque","");
            request.setAttribute("interior","");
          }
        }
        String strAddress  = (String)request.getParameter("dirEncasillada");
        if(strAddress == null)
          strAddress = objBeneVO.getDirEncasillada();
        
        request.setAttribute("dirEncasillada",strAddress);
        request.setAttribute("barrio",objBeneVO.getCodeBarrio());
        request.setAttribute("zona",objBeneVO.getCodeZona());
        request.setAttribute("cobama",objBeneVO.getCobama());
        request.setAttribute("sexo",objBeneVO.getSexo());
        request.setAttribute("comuna",objBeneVO.getVflComuna());
        request.setAttribute("mail",objBeneVO.getMail());
        request.setAttribute("etnia",objBeneVO.getEtnia());
        String[] fenac = {"00","00","00"};
        if(objBeneVO.getFechaNacimiento() != null){
          fenac = objBeneVO.getFechaNacimiento().split("/");
        }
        request.setAttribute("day",fenac[0]);
        request.setAttribute("month",fenac[1]);
        request.setAttribute("year",fenac[2]);
        request.setAttribute("beneSelected",beneSelected);
        try
        {
          BeneficiarioDAO objBeneDAO = new BeneficiarioDAO(cf);
          Collection grupo_familiar = objBeneDAO.getGrupoFamiliar(objBeneVO);
          cf.closeConnection(objBeneDAO.getConn());
          //session.setAttribute("grupo_familiar",grupo_familiar);
          request.setAttribute("grupo_familiar",grupo_familiar);
        }catch(SQLException e)
        {
			System.err.println("/******** TDSUB - cwsub");
			e.printStackTrace();
			System.err.println("TDSUB - cwsub ********/");
        }
        
        try
        {
          VflexDAO valorFlexDAO = new VflexDAO(cf); 
          comunas = valorFlexDAO.getVflex("COMUNA");
          barrios = valorFlexDAO.getVflex("BARRIO");
          zonas = valorFlexDAO.getVflex("ZONA");
          request.setAttribute("comunas",comunas);
          request.setAttribute("barrios",barrios);
          request.setAttribute("zonas",zonas);
          if((Object)opcion != null)
          {
            if(opcion.equals("zona"))
            {
              String codeZona = request.getParameter("codeZona");
              comunas = valorFlexDAO.getVflex("COMUNA",codeZona);
              barrios = valorFlexDAO.getVflex("BARRIO");
              request.setAttribute("comunas",comunas);
              request.setAttribute("barrios",barrios);
              request.setAttribute("zonas",zonas);
              request.setAttribute("zona",codeZona);
            }else if(opcion.equals("comuna"))
            {
              String codeComuna = request.getParameter("vflComuna");
              String codeZona = request.getParameter("codeZona");
              String zona = "";
              if(codeZona.equals(""))
              {
                 zona = valorFlexDAO.buscarPadre(codeComuna);
                 request.setAttribute("zona",zona);
              }else
              {
                 zona = codeZona;
                 request.setAttribute("zona",codeZona);
              }
              comunas = valorFlexDAO.getVflex("COMUNA",zona);
              barrios = valorFlexDAO.getVflex("BARRIO",codeComuna);
              request.setAttribute("comuna",codeComuna);
              request.setAttribute("comunas",comunas);
              request.setAttribute("barrios",barrios);
              request.setAttribute("zonas",zonas);
             
            }else if(opcion.equals("barrio"))
            {
              String codeComuna = request.getParameter("vflComuna");
              String codeZona = request.getParameter("codeZona");
              String codeBarrio = request.getParameter("codeBarrio");
              barrios = valorFlexDAO.getVflex("BARRIO");
              request.setAttribute("barrios",barrios);
              comunas = valorFlexDAO.getVflex("COMUNA");
              request.setAttribute("comunas",comunas);
              
              String zona = "";
              String comuna = "";
              comuna = valorFlexDAO.buscarPadre(codeBarrio);
              
              request.setAttribute("comuna",comuna);
              if(!comuna.equals(""))
                zona = valorFlexDAO.buscarPadre(comuna);
              request.setAttribute("zona",zona);
              request.setAttribute("barrio",codeBarrio);
            }
          }
          cf.closeConnection(valorFlexDAO.getConn());
        }catch(SQLException e)
        {
			System.err.println("/******** TDSUB - cwsub");
			e.printStackTrace();
			System.err.println("TDSUB - cwsub ********/");
        }
    }catch (UserException ue) 
		{
				messages.add("msgWarn",  new ActionMessage("loginForm.message."
																			+ ue.getExceptionVO().getId()));
				saveMessages(request, messages);
      	if(ue.getExceptionVO().getId()==AdministrationUserException.ENDED_SESSION)
        {       
              response.sendRedirect(request.getContextPath()+"/index.jsp");
        }
        else if(ue.getExceptionVO().getId()==CommonUserException.NOT_ALLOWED_RESOURCE)
        {
            response.sendRedirect(request.getContextPath()+"/admin/tile/invalidatedResource.jsp");
        }
        else
        {
            return mapping.getInputForward();
        }
      
    }
    
    

    return mapping.findForward("success");
  }
}